package org.alfresco.demo.rfernandes.cmdlineaction;

import java.util.List;

import org.alfresco.model.ContentModel;
import org.alfresco.repo.action.executer.ActionExecuterAbstractBase;
import org.alfresco.service.cmr.action.Action;
import org.alfresco.service.cmr.action.ParameterDefinition;
import org.alfresco.service.cmr.repository.ContentData;
import org.alfresco.service.cmr.repository.NodeRef;
import org.alfresco.service.cmr.repository.NodeService;
import org.apache.log4j.Logger;

/**
 * @author rfernandes
 * 
 */
public class CmdLineActionExecuter extends ActionExecuterAbstractBase {

	private String cmdLine;
	private NodeService nodeService;
	private boolean addBinaryContentStorePath = true;
	private static Logger logger = Logger
			.getLogger(CmdLineActionExecuter.class);

	public void setAddBinaryContentStorePath(boolean addBinaryContentStorePath) {
		this.addBinaryContentStorePath = addBinaryContentStorePath;
	}

	public void setNodeService(NodeService nodeService) {
		this.nodeService = nodeService;
	}

	public void setCmdLine(String cmdLine) {
		this.cmdLine = cmdLine;
	}

	@Override
	protected void executeImpl(Action action, NodeRef nodeRef) {

		CommandExecutor cmd = new CommandExecutor();
		cmd.execute(buildComdLine(nodeRef));

	}

	private String buildComdLine(NodeRef node) {
		String parsedCmdLine = addBinaryContentStorePath ? cmdLine+extractBinaryContentStorePath(node) : cmdLine;
		logger.info(String.format("Command line to execute: " + parsedCmdLine));
		return parsedCmdLine;
	}

	private String extractBinaryContentStorePath(NodeRef node) {
		String contentUrl = ((ContentData) nodeService.getProperty(node,
				ContentModel.PROP_CONTENT)).getContentUrl();
		contentUrl = contentUrl.substring(contentUrl.indexOf("://") + 3);
		logger.info(String.format("Binary content store URL fetched: "
				+ contentUrl));
		return contentUrl;
	}

	@Override
	protected void addParameterDefinitions(List<ParameterDefinition> params) {
		// do nothing

	}

}
